from aip import AipFace
import base64
import cv2


""" 你的 APPID AK SK """
APP_ID = '22912073'
API_KEY = '3zbPMNiqWOrsD5BspgX1pBoR'
SECRET_KEY = 'nxSoiCZnSdOV9DVTPhHrlMvAYvTHZNa4'

# 读取图片，转base64
filepath = r"face_test\1.jpg"
with open(filepath, "rb") as fp:
    base64_data = base64.b64encode(fp.read())
image = str(base64_data, 'utf-8')
imageType = "BASE64"

# aip_face对象
aipFace = AipFace(APP_ID, API_KEY, SECRET_KEY)

# 配置人脸检测参数
face_num = 10
options = {}
options["face_field"] = "age,beauty,gender,glasses,quality,eye_status,face_type"
options["max_face_num"] = face_num
options["face_type"] = "LIVE"
# options["liveness_control"] = "LOW"

# 调用接口进行检测
result = aipFace.detect(image, imageType, options)
result = result['result']

print(result)
face_list = result['face_list']  # 这里就是所有人脸的list，里面有各种数据
print(face_list)

# opencv画人脸检测框
img = cv2.imread(filepath)
color = (255, 0, 0)
for face in face_list:
    # 解析结果
    location = face['location']
    face_probability = face['face_probability']
    age = face['age']
    gender = face['gender']
    gender_type = gender['type']
    gender_probability = gender['probability']
    left = location['left']
    top = location['top']
    width = location['width']
    height = location['height']

    # 画图
    cv2.rectangle(img, (int(left), int(top)), (int(left+width), int(top+height)), (255, 0, 0))
    cv2.putText(img, gender_type, (int(left), int(top)), color=color, fontScale=1, fontFace=cv2.FONT_HERSHEY_SIMPLEX)
    cv2.putText(img, str(face_probability), (int(left+width), int(top)), color=color, fontScale=1, fontFace=cv2.FONT_HERSHEY_SIMPLEX)

# 测试input
input_str = input('please input')
print(input_str)

# 显示窗口
cv2.imshow('face_detection', img)
cv2.waitKey()
cv2.destroyAllWindows()
